<template>
  <div>
    <BreakSpace label="基本信息" :containerStyle="{ marginBottom: '10px' }"/>
    <FormPanel
      ref="baseInfo"
      :list="initFormBase"
      :cols="3"
      :labelWidth="180"
      :isSubmitBtn="false"
      :formType="handleType"
    />
    <BaseDialog :visible.sync="visbleVehicle" title="车辆选择"
                :containerStyle="{ overflow: 'auto', paddingBottom: '60px' }"
                destroyOnClose>
      <add-vehicle
        selectionType="single"
        @selectArr="selectVehicleFun"
        @closeDialog='visbleVehicle = false'></add-vehicle>
    </BaseDialog>
    <div class="dialogBottmView">
      <el-button @click="closeDialogTop()">返 回</el-button>
      <el-button v-if="handleType != 'show'" @click="saveDialog()" :loading="saveLoading" type="primary">
        保存
      </el-button>
      <el-button v-if="pageType == 'DLR1' && handleType !== 'show'" @click="saveDialog('T')" :loading="saveLoading" type="primary">
        提报
      </el-button>
    </div>
  </div>
</template>
<script>
import {dictionary} from '@/utils/dictMixin';
import {
  postSaveBatteryMaintenance,
  postUpdateStatusByIds,
  putBatteryMaintenance
} from '@/api/partsmanage/batteryTrace/batteryMaintenance';
import {dcqxqylxArr, ghnrArr} from './constant';
import addVehicle from '@/pages/partsmanage/purchaseManage/purchaseSubmit/addVehicle';
import {getDealerCompanyByCode,getDealerCompanyByCode1} from '@/api/part/exchange/platform';
import {getBatteryPlant} from '@/api/partsmanage/batteryTrace/batteryPlant';
import {dqArr} from "../batteryRecycle/constant";

export default {
  components: {
    addVehicle
  },
  props: {
    handleType: {
      type: String,
      default: 'add'
    },
    pageType: {
      type: String,
      default: ''
    },
    value: {
      type: Object,
      default: null
    }
  },
  mixins: [dictionary],
  data() {
    return {
      formData: {},
      initFormBase: this.initFormBaseFun(),
      visbleVehicle: false,
      saveLoading: false,
    };
  },
  mounted() {
    //判断是新增，还是修改
    this.getLeavePlants()
    if (this.handleType == 'add') {
      getDealerCompanyByCode().then(res => {
        const dealerInfo = res.data
        console.info("返回的数据")
        console.info(dealerInfo)
        this.formData.dealerCode = dealerInfo.dealerCode
        this.formData.dealerName = dealerInfo.dealerName
        this.formData.dealerAddr = dealerInfo.address
        this.init()
      })
    } else {
      this.formData = Object.assign({}, this.value.data);
      this.init();
      // getBatteryMaintenanceById(this.value.id).then(res => {
      //   if (res.resultCode === 200) {
      //     const data = Object.assign({}, this.formData, this.value.data, res.data);
      //     console.info(data)
      //     this.formData = data;
      //
      //   }
      // })
    }
  },
  computed: {
    culFormData() {
      return this.formData
    }
  },
  methods: {
    getLeavePlants() {
      getBatteryPlant({type: '1', available: true}).then(res => {
        if (res.resultCode == 200) {
          this.plantList = res.data
          const itemList = res.data.map(i => {
            return {
              text: i.name,
              value: i.id
            }
          })
          this.initFormBase.find(i => i.fieldName === 'whereaboutsPlantId').itemList = itemList
        }
      })
    },
    //修改时，初始化页面数据
    init() {
      //循环为表单赋值
      this.initFormBase.forEach(x => {
        if (this.culFormData[x.fieldName]) {
          x.initialValue = this.culFormData[x.fieldName];
        }
      });
    },
    changeQxcs(val) {
      let code = '';
      if (val) {
        code = this.plantList.find(i => i.id === val).socialCreditCode
      }
      this.initFormBase.find(i => i.fieldName === 'whereaboutsId').initialValue = code
    },
    //基本表单信息
    initFormBaseFun() {
      return [
        {
          type: 'INPUT',
          label: '电池维修登记单号',
          fieldName: 'maintenanceCode',
          placeholder: '请输入',
          hidden: this.handleType === 'add',
          initialValue: '',
          disabled: true
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入',
          initialValue: '',
          readonly: true,
          disabled: true,
          rules: [
            {required: true, trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: '经销商地址',
          fieldName: 'dealerAddr',
          placeholder: '请输入',
          initialValue: '',
          disabled: true,
          readonly: true,
          rules: [
            {required: true, trigger: 'change', message: '请输入'}
          ],
        },
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin',
          placeholder: '请选择',
          readonly: true,
          initialValue: '',
          rules: [
            {required: true, trigger: 'change', message: '请选择'}
          ],
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.visbleVehicle = true}></el-button>
              </div>
            );
          },
        },
        {
          type: 'SELECT',
          label: '更换内容',
          fieldName: 'batterySpecies',
          placeholder: '请选择',
          initialValue: '',
          itemList: ghnrArr,
          change: val => {
            this.changeBatterySpecies(val);
          },
          rules: [
            {required: true, message: '请选择', trigger: 'change'},
          ]
        },
        {
          type: 'DATE',
          label: '维修日期',
          fieldName: 'replaceDate',
          placeholder: '请输入',
          initialValue: '',
          format: 'yyyy-MM-dd',
          rules: [
            {required: true, trigger: 'change', message: '请选择维修日期'},
          ],
        },
        {
          type: 'INPUT',
          label: '客户姓名',
          fieldName: 'customerName',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            // {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '客户联系电话',
          fieldName: 'customerPhone',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            // {required: true, trigger: 'blur', message: '请输入'},
            {
              pattern: /^(([1][3,4,5,7,8][0-9]{9})|([0][1-9]{1}[0-9]{1,2}-[0-9]{5,10}))$/,
              message: '手机格式不正确',
              trigger: 'blur'
            }
          ]
        },
        {
          type: 'INPUT',
          label: '原电池包编码',
          fieldName: 'oldCode',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '新电池包编码',
          fieldName: 'newCode',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '原电池模块编码',
          fieldName: 'oldModuleCode',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '新电池模块编码',
          fieldName: 'newModuleCode',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '原电芯编码',
          fieldName: 'oldCellCode',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '新电芯编码',
          fieldName: 'newCellCode',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: false, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'SELECT',
          label: '原电池去向企业',
          fieldName: 'whereaboutsPlantId',
          placeholder: '请选择',
          initialValue: '',
          change: val => {
            this.changeQxcs(val);
          },
          itemList: [],
          rules: [
            {required: true, trigger: 'blur', message: '请选择'},
          ]
        },
        {
          type: 'INPUT',
          label: '去向企业统一社会信用代码',
          fieldName: 'whereaboutsId',
          placeholder: '请输入',
          initialValue: '',
          disabled: true
        },
        {
          type: 'SELECT',
          label: '电池去向企业类型',
          fieldName: 'destinationUnitType',
          placeholder: '请选择',
          initialValue: '',
          itemList: dcqxqylxArr,
          rules: [
            {required: true, message: '请选择', trigger: 'change'},
          ]
        },
        {
          type: 'SELECT',
          label: '电池去向企业所在地区',
          fieldName: 'destinationUnitArea',
          placeholder: '请选择',
          initialValue: '',
          itemList: dqArr,
          rules: [
            {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'SELECT',
          label: '维修更换地区',
          fieldName: 'repairArea',
          placeholder: '请选择',
          initialValue: '',
          itemList: dqArr,
          rules: [
            {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '维修更换地址',
          fieldName: 'repairAddress',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '维修服务商统一社会信用代码',
          fieldName: 'repairUnitCode',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
        {
          type: 'INPUT',
          label: '维修服务商名称',
          fieldName: 'repairUnitName',
          placeholder: '请输入',
          initialValue: '',
          rules: [
            {required: true, trigger: 'blur', message: '请输入'},
          ]
        },
      ];
    },
    changeBatterySpecies(batterySpecies) {
      ['oldModuleCode', 'newModuleCode', 'oldCellCode', 'newCellCode'].forEach(fieldName => {
        this.initFormBase.find(i => i.fieldName === fieldName).rules[0].required = false
      })
      if (batterySpecies === '' || batterySpecies === 'M') {
        ['oldModuleCode', 'newModuleCode'].forEach(fieldName => {
          this.initFormBase.find(i => i.fieldName === fieldName).rules[0].required = true
        })
      } else if (batterySpecies === '' || batterySpecies === 'C') {
        ['oldModuleCode', 'newModuleCode', 'oldCellCode', 'newCellCode'].forEach(fieldName => {
          this.initFormBase.find(i => i.fieldName === fieldName).rules[0].required = true
        })
      }
    },
    /*选择车辆信息回调 */
    selectVehicleFun(arr) {
      const vehicle = arr[0]
      this.visbleVehicle = false
      this.formData.vehicleId = vehicle.id
      // this.formData.vin = vehicle.vin
      this.initFormBase.find(i => i.fieldName === 'vin').initialValue = vehicle.vin
    },
    //保存
    async saveDialog(status = 'C') {
      this.saveLoading = true;
      if (this.handleType == 'show' && status === 'T') {
        return this.tbHandle(status)
      }
      let [err, data] = await this.$refs.baseInfo.GET_FORM_DATA();
      if (err) {
      } else {
        this.formData = Object.assign({}, this.formData, data);
        const formData = {
          ...this.culFormData,
          status
        }
        let res;
        if (this.handleType === "add") { // 新增
          res = await postSaveBatteryMaintenance(formData);
        } else { // 修改
          res = await putBatteryMaintenance(formData);
        }
        if (res.resultCode === 200) {
          this.$notify.success({title: '提示信息', message: status == 'T' ? '提报成功' : '保存成功!'});
          // 重新加载
          this.closeDialog('refresh');
        }
      }
      this.saveLoading = false;
    },
    // 提报
    async tbHandle(status) {
      this.saveLoading = true
      const res = await postUpdateStatusByIds({
        status,
        ids: [this.formData.id]
      })
      if (res.resultCode == 200) {
        this.$notify.success({title: '提示信息', message: '提报成功'});
        this.closeDialog('refresh');
      }
      this.saveLoading = false
    },
    closeDialogTop(confirm) {
      if (confirm) {
        this.$confirm('确认关闭窗口吗？您所做的操作将不会被保存！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.closeDialog('closeDialog');
        })
      } else {
        this.closeDialog('closeDialog');
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', type);
    }
  }
};
</script>

<style lang="less" scoped>
</style>
